//
//  MessageViewController.m
//  MyBlog
//
//  Created by NCS on 16/12/16.
//  Copyright © 2016年 YSL. All rights reserved.
//

#import "MessageViewController.h"
#import "AFNetworking.h"

@interface MessageViewController ()
@property (nonatomic, strong) UIImageView *leftImageView;
@property (nonatomic, strong) UIImageView *rightImageView;
//@property (nonatomic, strong) UIImageView *image;
@property (weak, nonatomic) IBOutlet UIImageView *image;

@end

@implementation MessageViewController

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Load webview
//    [self loadWebPage];
//    [self loadLocalPage];
    
    // ScrollView
    [self initScrollView];
    
//    _image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header"]];
    _image.image = [UIImage imageNamed:@"header"];
    _image.userInteractionEnabled = YES;
    [_image setFrame:CGRectMake(0, 400, SCREEN_WIDTH, 300)];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTap:)];
    
    [_image addGestureRecognizer:singleTap];
    [self.view addSubview:_image];
    
//    [self download];
    
}

- (void)downloadImage {
//        [[SDWebImageDownloader sharedDownloader] setValue:@"iPhone" forHTTPHeaderField:@"User-Agent"];
//    
//    //    http://img5.imgtn.bdimg.com/it/u=1614013440,1930745513&fm=21&gp=0.jpg
//    //    http://img3.imgtn.bdimg.com/it/u=3779691387,1388917972&fm=23&gp=0.jpg
//    //    http://img4.imgtn.bdimg.com/it/u=2586514090,3548971552&fm=23&gp=0.jpg
//         NSURL *url = [NSURL URLWithString:@"http://img3.imgtn.bdimg.com/it/u=3779691387,1388917972&fm=23&gp=0.jpg"];
//    
//        [self.msgImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"default"] options:SDWebImageRetryFailed];
}

- (void)initScrollView {
    [self loadData];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
    self.scrollView.delegate = self;
    self.scrollView.userInteractionEnabled = YES;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.scrollView setContentSize:CGSizeMake(SCREEN_WIDTH * self.items.count, 300)];
    
    [self loadScrollView];
    
    [self.view addSubview:self.scrollView];
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH / 2 - 160, 320, 40)];
    self.pageControl.numberOfPages = self.items.count - 2; // The first and last item is duplicate
}

- (void)loadData {
    self.items = [[NSMutableArray alloc] init];
    
    // Add the first pic
    NSString *firstImageName = @"headImg_3";
    UIImage *firstImage = [UIImage imageNamed:firstImageName];
    NSDictionary * firstDic = @{@"image":firstImage,@"title":firstImageName};
    [self.items addObject:firstDic];
    
    for (int i = 0; i < 3; i++) {
        NSString *imageName = [NSString stringWithFormat:@"headImg_%d", i + 1];
        UIImage *image = [UIImage imageNamed:imageName];
        
        NSDictionary * dic = @{@"image":image,@"title":imageName};
        
        [self.items addObject:dic];
        
    }
    
    // Add the first pic
    NSString *lastImageName = @"headImg_1";
    UIImage *lastImage = [UIImage imageNamed:lastImageName];
    NSDictionary * lastDic = @{@"image":lastImage,@"title":lastImageName};
    [self.items addObject:lastDic];
}

- (void)loadScrollView {
    for (int i = 0; i < self.items.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * i, 0, SCREEN_WIDTH, 300)];
        [imageView setImage:[self.items[i] valueForKey:@"image"]];
        
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTap:)];
        [imageView addGestureRecognizer:tap];
        
        [self.scrollView addSubview:imageView];
    }
}

- (void)imageTap:(id)sender {
    NSLog(@"image tap");
}

#pragma mark -- ScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    //获得偏移量
    CGPoint point = self.scrollView.contentOffset;
    //获得当前的最大x值(在可见区域内，最大的x轴上的值)
    CGFloat manX = self.scrollView.bounds.size.width * (self.items.count - 1);
    
    int index = point.x / self.scrollView.bounds.size.width;
    
//    [self.leftImageView setImage:[self.items[index] valueForKey:@"image"]];
    
    if (point.x > SCREEN_WIDTH) {
        NSLog(@" 右滑动	 -- %.2f", point.x);
    }else if (point.x < SCREEN_WIDTH) {
        NSLog(@" 左滑动   -- %.2f", point.x);
    }
    
    //如果当前点已经到了最前边的一张，即坐标为0,0
    if (point.x == 0)
    {
        CGFloat x = self.scrollView.bounds.size.width * (self.items.count - 2);
        [self.scrollView setContentOffset:CGPointMake(x , 0)];//立马跳到倒数第二张(因为最后一张是为了往后滚动做的铺垫视图)
    }
    
    //如果当前点已经达到最后一张图，即坐标为
    else if (point.x == manX)
    {
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width, 0)];//立马跳到整数第二张，第一张同理，利用人的视觉差
    }
    
    
//    //设置pageControl的点数
//    int pageNumber = [self imageIndexWithContentOffset:scrollView.contentOffset];//自定义方法，根据偏移量设置当前页码
//    self.pageControl.currentPage = pageNumber;
//    
//    //改变标签
//    int index = pageNumber + 1;
//    self.label.text = [self.items[index] objectForKey:@"title"];
}


//- (void)loadWebPage {
//    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [self.webView loadRequest:request];
//}
//
//- (void)loadLocalPage {
//    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"login" ofType:@"html"];
//    NSString* appHtml =[NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
//    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
//    [self.webView loadHTMLString:appHtml baseURL:baseURL];
//}


- (void)download {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"https://codeload.github.com/AFNetworking/AFNetworking/zip/master"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    // progress
    UIProgressView *progress = [[UIProgressView alloc] initWithFrame:CGRectMake(20, 350, SCREEN_WIDTH - 40, 30)];
//    [progress setTrackTintColor:[UIColor blueColor]];
    
    [self.view addSubview:progress];
//    progress.hidden = YES;
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            progress.hidden = NO;
            [progress setProgress:downloadProgress.fractionCompleted];
            NSLog(@"%.f", downloadProgress.fractionCompleted * 100);
        });
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    
    [downloadTask resume];
}

@end
